﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Resources;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Converter;
using csla4Skeleton.UI.SL.Resources.Utility;
using csla4Skeleton.UI.SL.DanhMuc.DM_HangHoa;
using csla4Skeleton.UI.SL.DanhMuc.DM_Kho;
using csla4Skeleton.UI.SL.NghiepVu.Kho.K_ListNhapKho;
using csla4Skeleton.UI.SL.NghiepVu.Kho.K_ListXuatKho;
using csla4Skeleton.UI.SL.NghiepVu.Kho.K_TonKho;
using csla4Skeleton.UI.SL.HeThong.HT_ThongTinCongTy;
using csla4Skeleton.UI.SL.NghiepVu.BanSanPham.BSP_BanHangHoa;
using Accounting.Library;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.GridView;
using System.ComponentModel;
using Utility;
using Accounting.Library.Utility;

namespace csla4Skeleton.UI.SL.TongHop.TH_KyGiaVon
{
    public partial class TH_KyGiaVon_MainWindow: UserControl, Csla.Xaml.ISupportNavigation
    {

        #region ISupportNavigation Members
        List<Control> controls = new List<Control>();
        bool DaTinhKyGiaVon = false;
        public bool CreateBookmarkAfterLoadCompleted
        {
            get { return true; }
        }

        public event EventHandler LoadCompleted;

        protected virtual void OnLoadCompleted()
        {
            if (LoadCompleted != null)
                LoadCompleted(this, EventArgs.Empty);
        }

        public void SetParameters(string parameters)
        {
            try
            {
                if (parameters == "")
                    Khoa = null;
                else
                    Khoa = Int32.Parse(parameters);
            }
            catch
            {
                Khoa = null;
            }
        }

        public string Title
        {
            get { return "KyGiaVon"; }
        }

       
        #endregion

        #region Load Methods
        private System.Nullable<int> Khoa = null;
        List<K_KhoInfo> NewListKyGiaVon = new List<K_KhoInfo>();
        public TH_KyGiaVon_MainWindow(int Khoa)          
        {
            this.Khoa = Khoa;
        }

        public TH_KyGiaVon_MainWindow()
        {
            LocalizationConverter converter = new LocalizationConverter();
            converter.LocalResourceManager = new ResourceManager("csla4Skeleton.UI.SL.TongHop.TH_KyGiaVon.Resources", Assembly.GetExecutingAssembly());
            this.Resources.Add("Localization", converter);
            
            InitializeComponent();
            ControlBehavior.ControlBehaviors.Navigation(this.TH_KyGiaVon_GeneralInformation_GroupBox, controls);
            
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
            {
                
                System.Windows.Data.CollectionViewSource TH_KyGiaVon_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["TH_KyGiaVon_ViewModelSource"];
                if (Khoa == null)
                {
                    TH_KyGiaVon_ViewModel TH_KyGiaVon_ViewModel = new TH_KyGiaVon_ViewModel();
                    TH_KyGiaVon_ViewModel.ChildList_AddedNew += new TH_KyGiaVon_ViewModel.ChildList_AddedNew_EventHandler(TH_KyGiaVon_ViewModel_ChildList_AddedNew);
                    TH_KyGiaVon_ViewModel.TimeChanged += new EventHandler(OnTimeChanged);
                    TH_KyGiaVon_ViewModel.CountChanged += new EventHandler(OnCountChanged);
                    TH_KyGiaVon_ViewModel.LoadCompleted +=new EventHandler(TH_KyGiaVon_ViewModel_LoadCompleted);
                    TH_KyGiaVon_CollectionViewSource.Source = new List<object> { TH_KyGiaVon_ViewModel };

                    
                }
                else
                {
                    TH_KyGiaVon_ViewModel TH_KyGiaVon_ViewModel = new TH_KyGiaVon_ViewModel((int)Khoa);
                    TH_KyGiaVon_ViewModel.ChildList_AddedNew += new TH_KyGiaVon_ViewModel.ChildList_AddedNew_EventHandler(TH_KyGiaVon_ViewModel_ChildList_AddedNew);
                    TH_KyGiaVon_ViewModel.TimeChanged += new EventHandler(OnTimeChanged);
                    TH_KyGiaVon_ViewModel.CountChanged += new EventHandler(OnCountChanged);
                    TH_KyGiaVon_ViewModel.LoadCompleted += new EventHandler(TH_KyGiaVon_ViewModel_LoadCompleted);
                    TH_KyGiaVon_CollectionViewSource.Source = new List<object> { TH_KyGiaVon_ViewModel }; 
                }

                System.Windows.Data.CollectionViewSource dm_HangHoa_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["DM_HangHoa_ListViewModelSource"];
                DM_HangHoa_ListViewModel dm_HangHoa_ListViewModel = new DM_HangHoa_ListViewModel(BusinessConfiguration.Configuration.ComboboxFetchMode);
                dm_HangHoa_CollectionViewSource.Source = new List<object> { dm_HangHoa_ListViewModel };

               

                System.Windows.Data.CollectionViewSource k_ListNhapKho_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["K_ListNhapKho_ListViewModelSource"];
                K_ListNhapKho_ListViewModel k_ListNhapKho_ListViewModel = new K_ListNhapKho_ListViewModel(DateTime.Now);
                k_ListNhapKho_CollectionViewSource.Source = new List<object> { k_ListNhapKho_ListViewModel };

                System.Windows.Data.CollectionViewSource k_ListXuatKho_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["K_ListXuatKho_ListViewModelSource"];
                K_ListXuatKho_ListViewModel k_ListXuatKho_ListViewModel = new K_ListXuatKho_ListViewModel(DateTime.Now);
                k_ListXuatKho_CollectionViewSource.Source = new List<object> { k_ListXuatKho_ListViewModel };

                System.Windows.Data.CollectionViewSource k_TonKho_ThangTruoc_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["K_TonKho_ThangTruoc_ViewModelSource"];
                K_TonKho_ViewModel k_TonKho_ThangTruoc_ViewModel = new K_TonKho_ViewModel(DateTime.Now.AddMonths(-1));
                k_TonKho_ThangTruoc_CollectionViewSource.Source = new List<object> { k_TonKho_ThangTruoc_ViewModel };

               
                /*
                System.Windows.Data.CollectionViewSource dm_Kho_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["DM_Kho_ListViewModelSource"];
                DM_Kho_ListViewModel dm_Kho_ListViewModel = new DM_Kho_ListViewModel(BusinessConfiguration.Configuration.ComboboxFetchMode);
                dm_Kho_CollectionViewSource.Source = new List<object> { dm_Kho_ListViewModel };*/

                this.TH_KyGiaVon_KyGiaVonChiTietGridView.KeyboardCommandProvider = new ControlBehavior.GridViewKeyboardCommandProvider(this.TH_KyGiaVon_KyGiaVonChiTietGridView);

                ((ControlBehavior.GridViewKeyboardCommandProvider)this.TH_KyGiaVon_KyGiaVonChiTietGridView.KeyboardCommandProvider).ReachLastColumn += new ControlBehavior.GridViewKeyboardCommandProvider.ReachLastColumn_EventHandler(OnReachLastColumn);
    
            }
        }

        #endregion
       

        #region Event Handle
        private void LayoutRoot_KeyUp(object sender, KeyEventArgs e)
        {
            if (Keyboard.Modifiers == ModifierKeys.Control)
            {
                TH_KyGiaVon_ViewModel vm = GetViewModel();
                if (e.Key == Key.S)
                {
                    if (vm.CanSave)
                    {
                        vm.Save(sender, new Csla.Xaml.ExecuteEventArgs());
                    }
                }
               
                else if (e.Key == Key.D1)
                {
                    this.TH_KyGiaVon_KyGiaVonChiTietTab.IsSelected = true;
                }
               
               
                
            }
            e.Handled = true;
        }

        private RadGridView GetActiveGridView()
        {
            if (this.TH_KyGiaVon_KyGiaVonChiTietTab.IsSelected)
            {
                return TH_KyGiaVon_KyGiaVonChiTietGridView;
            }
          
  
            return null;
        }



           
        void GridView_AddingNewDataItem(object sender, GridViewAddingNewEventArgs e)
        {
            var grid = e.OwnerGridViewItemsControl;
            if (grid.Items.Count > 0)
            {
                GridViewUtil.FocusRow((RadGridView)grid, grid.Items.Count - 1);
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    grid.CurrentCellInfo = new GridViewCellInfo(grid.Items[grid.Items.Count - 1], grid.Columns[0]);
                    grid.Focus();
                    grid.BeginEdit();
                }));
            }
        }
              
        private void SaveAndNewButton_Click(object sender, RoutedEventArgs e)
        {
           TH_KyGiaVon_ViewModel vm = GetViewModel();
            vm.SaveAndNew();
        }

        private void DatePicker_KeyUp(object sender, KeyEventArgs e)
        {
            List<Control> availableControl = new List<Control>();
            foreach (Control item in controls)
            {
                if (item.Visibility == System.Windows.Visibility.Visible)
                {
                    availableControl.Add(item);
                }
            }
            Control[] list = availableControl.ToArray();
            if (sender.GetHashCode() == list[availableControl.Count - 1].GetHashCode())
            {
                if (e.Key == Key.Enter)
                {
                    this.AddKyGiaVonDetailsItem();
                }
            }
            else
            {
                ControlBehavior.DatePickerBehaviors.DatePicker_KeyUp(sender, e, controls);
            }
        }

        private void ComboBox_KeyUp(object sender, KeyEventArgs e)
        {
            List<Control> availableControl = new List<Control>();
            foreach (Control item in controls)
            {
                if (item.Visibility == System.Windows.Visibility.Visible)
                {
                    availableControl.Add(item);
                }
            }
            Control[] list = availableControl.ToArray();
            if (sender.GetHashCode() == list[availableControl.Count - 1].GetHashCode())
            {
                if (e.Key == Key.Enter)
                {
                    this.AddKyGiaVonDetailsItem();
                }
            }
            else
            {
                ControlBehavior.ComboBoxBehaviors.ComboBox_KeyUp(sender, e, controls);
            }
        }

        private void Control_KeyUp(object sender, KeyEventArgs e)
        {
            List<Control> availableControl = new List<Control>();
            foreach (Control item in controls)
            {
                if (item.Visibility == System.Windows.Visibility.Visible)
                {
                    availableControl.Add(item);
                }
            }
            Control[] list = availableControl.ToArray();
            if (sender.GetHashCode() == list[availableControl.Count - 1].GetHashCode())
            {
                if (e.Key == Key.Enter)
                {
                    this.AddKyGiaVonDetailsItem();
                }
            }
            else
            {
                ControlBehavior.ControlBehaviors.Control_KeyUp(sender, e, controls);
            }
        }

    

        void OnReachLastColumn(object sender, ReachLastColumnArgs e)
        {

            this.tabControl.SelectedItem = tabControl.Items[0];
            FocusAfterChangeTab(this.TH_KyGiaVon_KyGiaVonChiTietGridView, e.Index);
        }

        private void FocusAfterChangeTab(GridViewDataControl grid, int index)
        {

            Dispatcher.BeginInvoke(new Action(() =>
            {
                grid.CurrentCellInfo = new GridViewCellInfo(grid.Items[index], grid.Columns[0]);
                grid.Focus();
                grid.BeginEdit();
            }));


        }
        

        #endregion

        #region View Model Related Methods
        private TH_KyGiaVon_ViewModel GetViewModel()
        {
            System.Windows.Data.CollectionViewSource TH_KyGiaVon_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["TH_KyGiaVon_ViewModelSource"];
            return ((List<object>)TH_KyGiaVon_CollectionViewSource.Source)[0] as TH_KyGiaVon_ViewModel;
        }

        public void TH_KyGiaVon_ViewModel_LoadCompleted(object sender, EventArgs e)
        {
            System.Windows.Data.CollectionViewSource ht_ThongTinCongTy_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["HT_ThongTinCongTy_ListViewModelSource"];
            HT_ThongTinCongTy_ListViewModel ht_ThongTinCongTy_ListViewModel = new HT_ThongTinCongTy_ListViewModel(BusinessConfiguration.Configuration.GridViewFetchMode);
            ht_ThongTinCongTy_ListViewModel.LoadCompleted += new EventHandler(ht_ThongTinCongTy_ListViewModel_LoadCompleted);
            ht_ThongTinCongTy_CollectionViewSource.Source = new List<object> { ht_ThongTinCongTy_ListViewModel };
        }
        public void OnTimeChanged(object sender, EventArgs e)
        {

            System.Windows.Data.CollectionViewSource k_ListXuatKho_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["K_ListXuatKho_ListViewModelSource"];
            K_ListXuatKho_ListViewModel k_ListXuatKho_ListViewModel = new K_ListXuatKho_ListViewModel(this.GetViewModel().Model.NgayTao);
            k_ListXuatKho_CollectionViewSource.Source = new List<object> { k_ListXuatKho_ListViewModel };

            System.Windows.Data.CollectionViewSource k_ListNhapKho_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["K_ListNhapKho_ListViewModelSource"];
            K_ListNhapKho_ListViewModel k_ListNhapKho_ListViewModel = new K_ListNhapKho_ListViewModel(this.GetViewModel().Model.NgayTao);
            k_ListNhapKho_CollectionViewSource.Source = new List<object> { k_ListNhapKho_ListViewModel };

            System.Windows.Data.CollectionViewSource k_TonKho_ThangTruoc_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["K_TonKho_ThangTruoc_ViewModelSource"];
            K_TonKho_ViewModel k_TonKho_ThangTruoc_ViewModel = new K_TonKho_ViewModel(this.GetViewModel().Model.NgayTao.AddMonths(-1));
            k_TonKho_ThangTruoc_CollectionViewSource.Source = new List<object> { k_TonKho_ThangTruoc_ViewModel };


        }
     

       
        private void AddKyGiaVonDetailsItem()
        {
            GetViewModel().AddTH_KyGiaVon_ChiTietItem();
            
        }

        private void DeleteKyGiaVonDetailsItem(int Index)
        {
            GetViewModel().DeleteTH_KyGiaVon_ChiTietItem( Index);
        }


        void TH_KyGiaVon_ViewModel_ChildList_AddedNew(object sender, ChildListAddedNewArgs e)
        {
            if (e.ChildListName == "TH_KyGiaVon_ChiTiets")
            {
                this.TH_KyGiaVon_KyGiaVonChiTietGridView.OnAddingNewDataItem(new GridViewAddingNewEventArgs(GetActiveGridView()));
            } 
        }
        #endregion

        private void TinhKyGiaVon_Click(object sender, RoutedEventArgs e)
        {
           
            IList<K_ListNhapKhoInfo> listNhapKho = null;
            
            System.Windows.Data.CollectionViewSource k_ListNhapKho_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["K_ListNhapKho_ListViewModelSource"];
            K_ListNhapKho_ListViewModel k_ListNhapKho_ListViewModel = ((List<object>)k_ListNhapKho_CollectionViewSource.Source)[0] as K_ListNhapKho_ListViewModel;

            if (k_ListNhapKho_ListViewModel.Model != null)
            {
                listNhapKho = k_ListNhapKho_ListViewModel.Model.getListOfInfo();
            }

            List<K_KhoInfo> listHangTonVaNhap = new List<K_KhoInfo>();

            if (listNhapKho != null)
            {
                foreach (K_ListNhapKhoInfo item in listNhapKho)
                {
                    bool IsExist = false;
                    foreach (K_KhoInfo KhoInfo in listHangTonVaNhap)
                    {
                        if (KhoInfo.HangHoaId == item.HangHoaId)
                        {
                            IsExist = true;
                            if (item.SoLuong != null)
                            {
                                KhoInfo.DonGia = (KhoInfo.DonGia * KhoInfo.SoLuong + item.SoLuong * item.DonGiaQĐ) / (item.SoLuong + KhoInfo.SoLuong);
                                KhoInfo.SoLuong += item.SoLuong.Value;
                                break;
                            }
                        }
                    }
                    if (!IsExist)
                    {
                        K_KhoInfo khoInfo = new K_KhoInfo(item.HangHoaId, item.SoLuong, item.DonGiaQĐ);
                        listHangTonVaNhap.Add(khoInfo);
                    }
                }
            }


            System.Windows.Data.CollectionViewSource K_TonKho_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["K_TonKho_ThangTruoc_ViewModelSource"];
            K_TonKho_ViewModel K_TonKho_ViewModel = ((List<object>)K_TonKho_CollectionViewSource.Source)[0] as K_TonKho_ViewModel;


            int countListHangTonVaNhap = listHangTonVaNhap.Count;

            //if (K_TonKho_ViewModel.Model.Khoa != 0)
            //{
            //    foreach (K_TonKho_ChiTietChild item in K_TonKho_ViewModel.Model.K_TonKho_ChiTiets)
            //    {
            //        bool IsHangHoaExist = false;
            //        for (int i = 0; i < countListHangTonVaNhap; i++)
            //        {
            //            if (listHangTonVaNhap[i].HangHoaId == item.HangHoaId)
            //            {
            //                listHangTonVaNhap[i].DonGia = (listHangTonVaNhap[i].DonGia * listHangTonVaNhap[i].SoLuong + item.SoLuong * item.DonGia) / (item.SoLuong + listHangTonVaNhap[i].SoLuong);
            //                listHangTonVaNhap[i].SoLuong += item.SoLuong;
            //                IsHangHoaExist = true;
            //                break;
            //            }
            //        }
            //        if (!IsHangHoaExist)
            //        {
            //            K_KhoInfo khoInfo = new K_KhoInfo(item.HangHoaId, item.SoLuong);
            //            listHangTonVaNhap.Add(khoInfo);
            //        }
            //    }
            //}
            
            foreach (K_KhoInfo item in listHangTonVaNhap)
            {
                NewListKyGiaVon.Add(item);
                this.AddKyGiaVonDetailsItem();
            }
            DaTinhKyGiaVon = true;
            this.TinhKyGiaVonButton.IsEnabled = false;

        }

        public void OnCountChanged(object sender, EventArgs e)
        {
            IList<TH_KyGiaVon_ChiTietChild> listChiTiet = this.GetViewModel().Model.TH_KyGiaVon_ChiTiets;
            if (listChiTiet.Count == NewListKyGiaVon.Count)
            {
                int index = 0;
                foreach (TH_KyGiaVon_ChiTietChild item in listChiTiet)
                {
                    item.HangHoaId = NewListKyGiaVon[index].HangHoaId;
                    item.DonGia = NewListKyGiaVon[index].DonGia;

                    System.Windows.Data.CollectionViewSource dm_HangHoa_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["DM_HangHoa_ListViewModelSource"];
                    DM_HangHoa_ListViewModel dm_HangHoa_ListViewModel = ((List<object>)dm_HangHoa_CollectionViewSource.Source)[0] as DM_HangHoa_ListViewModel;
                    IList<DM_HangHoaInfo> listHangHoa = dm_HangHoa_ListViewModel.Model.getListOfInfo();

                    //foreach(DM_HangHoaInfo HangHoaItem in listHangHoa)
                    //{
                    //    if(HangHoaItem.Khoa == NewListKyGiaVon[index].HangHoaId)
                    //    {
                    //        item.DienGiai = HangHoaItem.TenViet;
                    //        break;
                    //    }

                    //}
                    index++;
                }
            }
            

        }
        

        public void ht_ThongTinCongTy_ListViewModel_LoadCompleted(object sender, EventArgs e)
        {
            System.Windows.Data.CollectionViewSource ht_ThongTinCongTy_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["HT_ThongTinCongTy_ListViewModelSource"];
            HT_ThongTinCongTy_ListViewModel ht_ThongTinCongTy_ListViewModel = ((List<object>)ht_ThongTinCongTy_CollectionViewSource.Source)[0] as HT_ThongTinCongTy_ListViewModel;
            if (ht_ThongTinCongTy_ListViewModel.Model.getListOfInfo().Count != 0 && ht_ThongTinCongTy_ListViewModel.Model.getListOfInfo()[0].PhuongPhapTinhGiaVonId == 4)
            {
                if (this.GetViewModel().Model != null )
                {
                    if (this.GetViewModel().Model.TH_KyGiaVon_ChiTiets.Count == 0)
                    {
                        this.TinhKyGiaVonButton.IsEnabled = true;
                        this.BoTinhKyGiaVonButton.IsEnabled = false;
                    }
                    else
                    {
                        this.TinhKyGiaVonButton.IsEnabled = false;
                        this.BoTinhKyGiaVonButton.IsEnabled = true;
                    }
                }
            }
            
        }

        private void BoTinhKyGiaVon_Click(object sender, RoutedEventArgs e)
        {
            int count = this.GetViewModel().Model.TH_KyGiaVon_ChiTiets.Count;
            for (int i = count - 1; i >=0; i--)
            {
                this.DeleteKyGiaVonDetailsItem(i);
            }
            this.DaTinhKyGiaVon = false;
            this.BoTinhKyGiaVonButton.IsEnabled = false;
        }

        private void SaveButtonClick(object sender, RoutedEventArgs e)
        {
            this.GetViewModel().SaveKyGiaVon();
            if (DaTinhKyGiaVon)
            {
                this.TinhKyGiaVonButton.IsEnabled = false;
                this.BoTinhKyGiaVonButton.IsEnabled = true;
            }
            else
            {
                this.TinhKyGiaVonButton.IsEnabled = true;
                this.BoTinhKyGiaVonButton.IsEnabled = false;
            }
        }
        
    }
}
